/*
 * @authors :Bin Mei
 * @date    :2017-7-27
 * @description：app  -> 账户页
 */

import React, { Component} from 'react';
import {bindActionCreators} from "redux";
import {connect} from "react-redux";
import { Link } from 'react-router';
import classnames from 'classnames';
import ReactEcharts from 'echarts-for-react';
import actions from "src/store/actions";
import {Panel,Modal,Button,Icon,Cell,Input,StaticToast} from 'pjh-mobile-ui';
import {Classify,Count,Empty,Svg } from "src/components/common";
import { mFormat,mEvents,mBridge,mFetch,mStorage,minHistory} from 'min-bridge';

import format from "src/utils/format";
import dia from "src/utils/dia";

import './Index.scss';

let Storage_Key = 'eye_type';
const svghash={
	1:"#svg-ttz-icon",
	2:"#svg-bbk-icon",
	3:"#svg-adq-icon",
}
const symbol={//*号 眼睛开关 *号位数
	4:"****",
	6:"******",
}

class Accounts extends Component{
	constructor(props){
		super(props);
			this.state = {
				eye:mStorage.get(Storage_Key)||1, //账户首页的眼睛开关操作 1-开，2-关
			};

	}
	componentWillMount(){
		this.setEye();
	}
	componentDidMount(){
		let {ACTIONS} = this.props;
		ACTIONS.account_home();
	}
	componentWillUnmount(){
		this.setEye('CLOSE');//页面退出前，关闭右上角菜单
	}
	setEye(flag){
		let {eye} = this.state;
		window.appEyeHandler=()=>{
			this.eyeHandler();
		};
		mBridge.setAppRightMenu&&mBridge.setAppRightMenu({
      type:flag||'OPEN',
      position:"CENTER",
      action:[{
        type:"CLICK",
        status:(eye==1?"OPEN":"CLOSE"),
        events:"appEyeHandler"
      }]
		})
		/*window.accountHomePull =()=>{
			this.getData();
		}
		//开启下拉刷新
		mBridge.setPullDown&&mBridge.setPullDown({
			type:flag||'OPEN',
			action:'accountHomePull'
		});*/
	}
	eyeHandler(){
		//眼睛开关操作
		let {eye} = this.state;
		let {ACTIONS,toggle} = this.props;
		mStorage.set(Storage_Key,eye==1?2:1);
		this.setState({
			eye:eye==1?2:1
		})
	}
	eyeToogle(data,symbolNum){
		let {eye} = this.state;
		if(eye==1){
			return mFormat.separator(data);
		}else{
			return (<em className="symbol">{symbol[symbolNum||4]}</em>);
		}
		
	}
	goUserCenter(){

		//跳转app原生页面，个人信息页 先调用关闭右上角菜单方法
		mBridge.goAppView&&mBridge.goAppView({
			type:"USERCENTER"
		})
	}

	jumpPage(type) {
		const { _account } = this.props;
		if (_account.user.isReal != 1) {
			StaticToast.info('你还未认证绑卡，请先绑卡', () => {
				minHistory.push({ pathname: '/app/user/bindBank', query: { backTo: location.href } });
			});
		}else{
			minHistory.push({ pathname: `/app/account/${type == 1 ? 'withdrawals' : 'recharge'}` });
		}
	}
	render(){

		let {eye} = this.state;
		let {_account,toggle}=this.props;
		if(!Object.keys(_account).length){
			return (<Empty/>);
		}
		return ( 
			<div className="user-account">
					<Cell type="link" className="a-base mb10" title={_account.user.phone} icon={<img className="user_icon" src={_account.user.headImage} />} onClick={() =>this.goUserCenter()} />
					<section className="cast-info mb10">
						<h3 className="subtit">累计已投 (元)</h3>
						<p className="c-money">
							{
							eye==1?(
								<Count 
							start={0} end={_account.totalInvestment.amount} duration={1} />
							):(
								this.eyeToogle((_account.totalInvestment.amount),6)
							)
							}
							
						</p>
						<div className="echarts ds-box">
							<div className="left cm-flex flex-y">
								{
									_account.totalInvestment.list.map((item,i)=>{
										return (
											<p key={i} className={classnames("class",{[`i${i}`]:true})}><Svg className="icons" hash={svghash[item.projectType]}/>{format.projectType(item.projectType)} <span className="i-money">{this.eyeToogle((item.amount)) }</span></p>
										);
									})
								}
							</div>
							<div className="flex-y" style={{width:"45%"}}>
								<RaderChart {...this.props}/>
							</div>
						</div>
					</section>
					<Cell type="link" className="a-base mb10 hide" title=""   onClick={() =>{}} >
						<p className="exceed">你已超过<em className="ratio">{_account.totalInvestment.ratio}%</em>的用户</p>
					</Cell>
					<section className="property mb10">
						<BaseInfo title="现有资产" num={this.eyeToogle((_account.totalAssets.amount),6)}/>
						<Link to={{pathname:"/app/account/possess"}}>
							<Classify className="property-class" separator={false} data={[
								{title:"可用余额",value:(this.eyeToogle(_account.totalAssets.balance))},{title:"待收本金",value:(this.eyeToogle(_account.totalAssets.dueInCapital))},
							]} />
						</Link> 
						<section className="other">
							<h6 className="i6-tit">{_account.totalAssets.freeze!=0&&(`冻结${this.eyeToogle(_account.totalAssets.freeze)}`)}</h6>
							<div className="ds-box">
								<p className="cm-flex" onClick={e => this.jumpPage(1)}><span to="/app/account/withdrawals" className="button border">提现</span></p>
								<p className="cm-flex" onClick={e => this.jumpPage(2)}><span to="/app/account/recharge" className="button fill" >充值</span></p>
							</div>
						</section>
					</section>
					<section className="earnings mb10">
						<Cell type="link" title="昨日收益" onClick={() =>{minHistory.push({pathname:"/app/account/earnings"})}}>
							<p className="earnings-num">+{this.eyeToogle(_account.incomeEarned.yesterEarnings)}</p>
						</Cell>
						<BaseInfo title="累计已赚" num={this.eyeToogle((_account.incomeEarned.amount),6)}/>
						<Classify className="earnings-class"  separator={false} data={[
								{title:"已赚利息",value:(this.eyeToogle(_account.incomeEarned.hasInterest))},{title:"已赚返利",value:(this.eyeToogle(_account.incomeEarned.hasRebate))},,{title:"已用红包",value:(this.eyeToogle(_account.incomeEarned.hasCoupon))}
							]}/>
					</section>
					<Cell type="link" className="mb10" title="红包" onClick={() =>{}}>
						<Link className="earnings-num flex-y" to="/app/account/coupon">+{this.eyeToogle((_account.couponBalance))}</Link>
					</Cell>
					<Cell type="link" title="回款计划" onClick={() =>{minHistory.push({pathname:"/app/account/returnCalendar"})}} />
					<Cell type="link" className="mb10" title="交易记录" onClick={() =>{minHistory.push({pathname:"/app/account/trading"})}}/>
			</div>
		);
	}
};

/*
*@ 累计已投 模块的图表展示
*/
class RaderChart extends Component{
	constructor(props){
		super(props);
	}
	getOptions(){
		const colors = {
			1:"#EF8200",
			2:"#18428d",
			3:"#3FC1CC",
			"d":"#ddd"
		}
		let {_account}=this.props;
		let {list} = _account.totalInvestment;
		let options = {
			color:(list||[]).map((item,i)=>{
				return  colors[(item.amount > 0 ? item.projectType:"d")];
			}),
				series: [
						{
								name:'累计已投',
								type:'pie', 
								radius: ['55%', '95%'],
								center:["50%","50%"],
								avoidLabelOverlap: false,
								hoverAnimation:false,
								label: {
										normal: {
												show: false,
												position: 'center'
										},
										emphasis: {
												show: false,
												textStyle: {
														fontSize: '30',
														fontWeight: 'bold'
												}
										}
								},
								labelLine: {
										normal: {
												show: false
										}
								},
								data:(list||[]).map((item,i)=>{
									return  item.amount||0;
								}),
						}
				]
		};
		// console.log(options)
		return options;
	}
	ready(echart){
		mEvents.on(window, 'resize', function(){
					echart.resize()
		});

	}

	render(){
		return(
			<div style={{width:"100%",height:"100%"}}>
				<ReactEcharts 
				option={this.getOptions()} 
				style={{minHeight:90}}			 
				onChartReady={this.ready} />
			</div>
		);
	}
};

/*
*@ 共用模块 基础信息展示部分
*/
const BaseInfo = (props)=>(
	<div className="bs-exhibit">
		<h4 className="i4-tit">{props.title}</h4>
		<p className="money-num">{props.num}</p>
	</div>
);

let mapStateToProps=(state)=>{
	let {account} = state.accountIndex;
	let toggle = state.userToggle;
	return {
		_account:account,
		toggle:toggle
	};
}; 

let mapDispatchToProps=(dispatch)=>{
	return {
		ACTIONS:bindActionCreators(actions,dispatch)
	};
};
export default connect(mapStateToProps,mapDispatchToProps)(Accounts);

